package com.dm.cloud.tkmybatis.config;

import com.github.pagehelper.PageInterceptor;
import com.dm.cloud.tkmybatis.service.BasePOInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author sg
 * @ClassName DataSourceTransactionManager.java
 * @desc
 * @Date 2021/08/18 17:46
 */
@Component
@EnableTransactionManagement
@Slf4j
public class DataSourceTransactionConfig extends DataSourceTransactionManagerAutoConfiguration {

    @Bean
    public Interceptor pageInterceptor() {
        return new PageInterceptor();
    }

    /**
     * 注入sql拦截器
     * @return
     */
    @Bean
    public Interceptor basePOInterceptor() {
        return new BasePOInterceptor();
    }

    @Bean
    @Autowired
    public SqlSessionFactory sqlSessionFactory(DataSource datasource,
                                               @Qualifier("basePOInterceptor") Interceptor basePOInterceptor) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(datasource);
        //分页的拦截器可以在此进行配置
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{basePOInterceptor});
        Configuration configuration = new Configuration();
        //使用jdbc的getGeneratedKeys获取数据库自增主键值
        configuration.setUseGeneratedKeys(true);
        //使用列别名替换列名，如：select user as User
        configuration.setUseColumnLabel(true);
        //自动使用驼峰命名属性映射字段，如userId    user_id
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    @Autowired
    public DataSourceTransactionManager transactionManager(DataSource datasource) {
        return new DataSourceTransactionManager(datasource);
    }
}